

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/2.jpg">
  <link rel="icon" type="image/png" href="/img/2.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="K">
  <meta name="keywords" content="">
  <title>JavaScript-ajax请求配置 - K</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>かい</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/1.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-11-05 14:50" pubdate>
        2020年11月5日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      11
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">JavaScript-ajax请求配置</h1>
            
            <div class="markdown-body" id="post-body">
              <h2 id="ajax请求参数格式"><a href="#ajax请求参数格式" class="headerlink" title="ajax请求参数格式"></a>ajax请求参数格式</h2><ul>
<li><p>post请求参数格式</p>
<ul>
<li><p>application/x-www-form-urlencoded </p>
<pre><code class="hljs dts"><span class="hljs-meta"># 格式样式</span>
name=lmk<span class="hljs-variable">&amp;age</span>=<span class="hljs-number">18</span><span class="hljs-variable">&amp;sex</span>=男</code></pre>
</li>
<li><p>application/json</p>
<pre><code class="hljs css">&#123;<span class="hljs-attribute">name</span>:<span class="hljs-string">&#x27;lmk&#x27;</span>,age:<span class="hljs-string">&#x27;18&#x27;</span>,sex:<span class="hljs-string">&#x27;男&#x27;</span>&#125;</code></pre>
</li>
<li><p>multipart/form-data</p>
</li>
<li><p>text/xml<br>这两个在请求的时候可能会不常用</p>
</li>
<li><p>json参数问题</p>
<ul>
<li>json参数传递时需要转成json字符串才可以传递参数（参数是以字符串的形式进行传递的）</li>
</ul>
<pre><code class="hljs pgsql"><span class="hljs-type">JSON</span>.stringify(); # 将<span class="hljs-type">json</span>对象转换成<span class="hljs-type">json</span>字符串</code></pre>
</li>
<li><p>get请求是不能提交json对象数据格式的，因为传统网站的表单提交是不支持json对象数据格式的</p>
</li>
</ul>
</li>
</ul>
<h2 id="获取服务端的响应信息"><a href="#获取服务端的响应信息" class="headerlink" title="获取服务端的响应信息"></a>获取服务端的响应信息</h2><ul>
<li><p>ajax状态码</p>
<ul>
<li>在创建ajax对象，配置ajax对象，发送请求，以及接受完客户端的响应数据时，这个过程中每一个步骤都会对应一个数值，这个数值就是ajax状态码<ul>
<li>0 请求初始化(还没有调用open)</li>
<li>1 请求已经建立,但是还没有发送（还没有调用send）</li>
<li>2 请求已经发送了</li>
<li>3 请求正在处理中，通常响应中已经有部分数据可以用了</li>
<li>4 响应已经完成，可以获取并使用服务器响应了</li>
</ul>
</li>
</ul>
</li>
<li><p>获取ajax状态码</p>
<pre><code class="hljs php">xhr.readyState <span class="hljs-comment"># 获取ajax状态码</span>
<span class="hljs-comment"># 由于请求发送时，状态码是不停变动的，所以提供了一个事件 &quot;onreadystatechange&quot; 当ajax状态码发生变化时自动触发改事件</span>
<span class="hljs-comment"># 定义事件，监听状态码</span>
xhr.addEventListener(<span class="hljs-string">&#x27;readystatechange&#x27;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;
    <span class="hljs-comment"># 这里面可以if判断，通过 xhr.readyState获取状态码，根据状态码进行相应的操作</span>
&#125;)</code></pre></li>
<li><p>onload 和 onreadystatechange的区别</p>
<ul>
<li>都可以返回服务端的响应信息</li>
<li>onload不兼容低版本的浏览器，不需要判断ajax状态码，每次只调用一次</li>
<li>onreadystatechange 兼容低版本浏览器，需要判断ajax状态码，能多次调用</li>
</ul>
<h2 id="ajax错误处理"><a href="#ajax错误处理" class="headerlink" title="ajax错误处理"></a>ajax错误处理</h2><ul>
<li>通常ajax发生错误，一般是这几个问题<br>1.网络畅通，服务器能够收到请求，服务器端反水的结果不是预期的结果<ul>
<li>可以判断ajax状态码，分别进行处理<pre><code class="hljs 1c">xhr.readyState <span class="hljs-meta"># 获取ajax状态码</span>
xhr.status <span class="hljs-meta"># 获取http状态码</span>
<span class="hljs-meta"># ajax状态码，表示ajax请求过程的状态，ajax对象返回的</span>
<span class="hljs-meta"># http状态码，表示请求的处理结果，服务器端返回的</span></code></pre></li>
</ul>
2.网络通畅，服务器没有接受到请求，返回404状态码<ul>
<li>检查请求地址是否错误</li>
</ul>
3.网络通畅，服务器能够接受到请求，但是返回了500状态码<ul>
<li>服务器错误，调试后端</li>
</ul>
4.网络中断，请求无法发送到服务端<ul>
<li>会触发xhr对象下面的onerror事件，在onerror事件处理函数进行处理</li>
<li>触发该事件的前提是要在前端ajax请求写上 error事件<pre><code class="hljs actionscript">xhr.addEventListener(<span class="hljs-string">&#x27;error&#x27;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">()</span></span>&#123;
    alert(<span class="hljs-string">&#x27;网络中断&#x27;</span>)
&#125;)</code></pre>

</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="ajax缓存问题"><a href="#ajax缓存问题" class="headerlink" title="ajax缓存问题"></a>ajax缓存问题</h2><ul>
<li>在ie低版本中 ajax有一个严重的缓存问题，即使在请求地址不发生变化的情况下，有一次记请求发送到了服务器，后续请求会直接从浏览器缓存中获取结果，即使服务器更新了该数据，但是客户端看到的依旧是旧的数据<ul>
<li>解决方法</li>
<li>在前端使用ajax发送请求时，加上随机参数，这样每次访问就不会从换从中提取数据了<pre><code class="hljs livecodeserver">xhr.<span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;get,&#x27;</span><span class="hljs-keyword">http</span>://<span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>/?=+Math.<span class="hljs-built_in">random</span>()) <span class="hljs-comment"># 使用随机数来发送请求，这样就不会有缓存问题了</span>
<span class="hljs-comment"># ie永远的神。。。。</span></code></pre>

</li>
</ul>
</li>
</ul>
<h2 id="同步和异步"><a href="#同步和异步" class="headerlink" title="同步和异步"></a>同步和异步</h2><ul>
<li>同步<ul>
<li>就是代码只有上一层执行后，下一层才会执行</li>
</ul>
</li>
<li>异步<ul>
<li>异步代码虽然会花时间去执行，但是主程序不回等待异步代码执行完后在继续执行后续代码，而是直接执行后面的代码，当后面的代码执行完毕后，才看看异步代码是否返回结果，如果有结果就直接调用结果，没有则等待完成</li>
</ul>
</li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/javascript/">javascript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/ajax/">ajax</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章是以学习为目的，如果有不对的地方可以一起交流沟通共同学习 邮箱:1248287831@qq.com！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/11/06/%E5%89%8D%E7%AB%AF%E5%B8%83%E5%B1%80-%E6%B5%81%E5%BC%8F%E5%B8%83%E5%B1%80/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">前端布局-流式布局</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/11/05/%E5%89%8D%E7%AB%AF%E8%AF%B7%E6%B1%82-ajax%E8%AF%B7%E6%B1%82/">
                        <span class="hidden-mobile">JavaScript-ajax请求</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://space.bilibili.com/39165374" target="_blank" rel="nofollow noopener"><span>LMK</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "JavaScript-ajax请求配置&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>















</body>
</html>
